package fr.channel.client.activity;

import java.util.List;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.inject.Inject;

import fr.channel.client.PartieService;
import fr.channel.client.PartieServiceAsync;
import fr.channel.client.ChannelTest;
import fr.channel.client.ClientFactory;
import fr.channel.client.event.MessageEvent;
import fr.channel.client.event.MessageHandler;
import fr.channel.client.metier.SmChannel;
import fr.channel.client.view.ConnectionView;
import fr.channel.shared.dto.PartieDTO;
import fr.channel.shared.dto.Reponse;

public class ConnectionActivity extends AbstractActivity implements ConnectionView.Presenter, MessageHandler {

	private ClientFactory clientFactory;

	// Create a remote service proxy to talk to the server-side service.
	private final PartieServiceAsync channelService = GWT.create(PartieService.class);

	private SmChannel smChannel;

	private EventBus eventBus;

	@Inject
	public ConnectionActivity(final ClientFactory pClientFactory, final SmChannel pSmChannel) {
		super();
		this.clientFactory = pClientFactory;
		this.smChannel = pSmChannel;
	}

	@Override
	public final void start(final AcceptsOneWidget panel, final EventBus pEventBus) {
		final ConnectionView connectionView = clientFactory.getConnectionView();
		connectionView.setPresenter(this);
		panel.setWidget(connectionView.asWidget());

		channelService.getParties(new AsyncCallback<List<PartieDTO>>() {

			@Override
			public void onFailure(final Throwable caught) {
				ChannelTest.log("Erreur recuperation des parties");
			}

			@Override
			public void onSuccess(final List<PartieDTO> result) {
				ChannelTest.log("Succes recuperation des parties");
				connectionView.setParties(result);
			}

		});

		this.eventBus = pEventBus;

	}

	@Override
	public void goTo(final Place place) {
		// TODO Auto-generated method stub

	}

	@Override
	public final void createPartie(final String partieName, final String joueurName) {
		channelService.createPartie(partieName, joueurName, new AsyncCallback<Reponse<String>>() {
			public void onFailure(final Throwable caught) {
				ChannelTest.log("Erreur connection");
			}

			public void onSuccess(final Reponse<String> reponse) {
				if (reponse.isSucess()) {
					smChannel.createChannel(reponse.getValue(), eventBus);
					ChannelTest.log("Sucess token : " + reponse.getValue());
				} else {
					ChannelTest.log("Erreur: " + reponse.getError());
				}
			}
		});

	}

	@Override
	public final void onNewMessage(final MessageEvent messageEvent) {
		ChannelTest.log("Message : " + messageEvent.getMessage());

	}

}
